<?php
use Carbon\Carbon;
class Order extends Eloquent {
	
	public static $rules = array(
		'order_number'=>'required|bigint',
		'customer_id'=>'required',
		'production_number'=>'required',
		'amount'=>'required|bigint',
		'order_date'=>'required|date_format:d/m/Y',
		'production_start_date'=>'required|date_format:d/m/Y',
		'production_end_date' => 'required|date_format:d/m/Y',
		'components'=>'componentsrequired|componentsnotempty',
		'amounts'=>'componentsrequired|componentsnotempty|componentsamount',
		'costCentres'=>'componentsrequired|componentsnotempty',
		'accessories'=>'accessoryCostsCentres:costCentres',
		'currentAccessories'=>'accessoryCostsCentres:currentCostsCentres'
	);
	
	protected $dates = array('order_date', 'production_start_date', 'production_end_date');
	
	public function components() {
		return $this->belongsToMany('Component', 'orders_components');
	}
	
	public function customer() {
		return $this->belongsTo('Customer');
	}
	
	public static function getOrders($options, $offset, $limit) {
		$where = array();
		$bindings = array();
	
		if (!empty($options['orderNumber'])) {
			$where[] = "order_number = :orderNumber";
			$bindings['orderNumber'] = $options['orderNumber'];
		}
	
		if (!empty($options['customerId'])) {
			$where[] = "customer_id = :customerId";
			$bindings['customerId'] = $options['customerId'];
		}
	
		if (!empty($options['onlyCompleted'])) {
		$where[] = "min_current_step = 99";
		}
	
		return Order::report(empty($where) ? "" : " WHERE " . join(" AND ", $where), $bindings, $offset, $limit);
	}
	
	public static function getExecutedOrders($options, $offset, $limit) {
		$where = array();
		$bindings = array();
		
		if (!empty($options['orderNumber'])) {
			$where[] = "order_number = :orderNumber";
			$bindings['orderNumber'] = $options['orderNumber'];
		}
		
		if (!empty($options['productionNumber'])) {
			$where[] = "production_number = :productionNumber";
			$bindings['productionNumber'] = $options['productionNumber'];
		}
		
		if (!empty($options['customerId'])) {
			$where[] = "customer_id = :customerId";
			$bindings['customerId'] = $options['customerId'];
		}
		
		$where[] = "min_current_step = 99";
		$where[] = "production_real_end_date >= DATE_SUB(current_date(), INTERVAL 30 DAY)";
		
		return Order::report(empty($where) ? "" : " WHERE " . join(" AND ", $where), $bindings, $offset, $limit);
	}
	
	public static function report($where, array $bindings, $offset, $limit) {
		$results = DB::select(DB::raw("
			SELECT
				SQL_CALC_FOUND_ROWS
				ordersWithTotals.*
				, c.name AS customer_name
			FROM (
				SELECT
					o.*
					, MIN(oc.current_step) AS min_current_step
					, MAX(ocl.created_at) AS production_real_end_date
				FROM
					orders o
					INNER JOIN orders_components oc ON (o.id = oc.order_id)
					LEFT JOIN order_component_logs ocl ON (oc.id = ocl.order_component_id)
				GROUP BY
					o.id
			) AS ordersWithTotals
				INNER JOIN customers c ON (c.id = ordersWithTotals.customer_id) 
				${where}
			ORDER BY
				order_number, production_number
			LIMIT
				:limit
			OFFSET
				:offset
		"),
		array_merge(
			$bindings,
			array(
				'limit' => $limit,
				'offset' => $offset
			)
		));
		
		$totalRows = DB::selectOne('SELECT FOUND_ROWS() AS total');
		
		return array(
			'total' => $totalRows->total,
			'data' => $results
		);
	}
	
	public static function assembleValidation(array $input) {
		$rules = Order::$rules;
		$rules['production_start_date'] = $rules['production_start_date'] . '|beforecustom:' . $input['production_end_date'];
		
		try {
			$startDate = Carbon::createFromFormat('d/m/Y', $input['production_start_date']);
			$endDate = Carbon::createFromFormat('d/m/Y', $input['production_end_date']);
			$daysBetween = $endDate->diffInDays($startDate) + 1;
			
			$rules['costCentres'] = $rules['costCentres'] . '|totalcc:' . $daysBetween; 
		} catch(InvalidArgumentException $x) {
			// esta valicao só deve ser inserida se as datas estiverem ok
		}

		return $rules;
	}
	
	public function canEditProductionStart() {
		return OrderComponent::where('order_id', '=', $this->id)->where('current_step', '>', 1)->count() === 0;
	}
	
}